package com.promise.jokerdream.network

import com.promise.jokerdream.response.parser.SimpleXmlParser
import kotlinx.coroutines.*
import okhttp3.Call
import okhttp3.Response
import java.io.IOException

/**
 * 支持自动重试的HTTP回调包装器（手机端专用）
 * 当响应的XML内容包含特定错误信息时，会自动重新发起请求
 */
class PhoneRetryableHttpCallback(
    private val originalCallback: IHttpCallback,
    private val maxRetries: Int = 10,
    private val retryDelay: Long = 1000L,
    private val retryRequest: () -> Unit
) : IHttpCallback {
    
    private var currentRetryCount = 0
    
    // 使用全局协程作用域，避免内存泄漏
    private val retryScope = CoroutineScope(Dispatchers.IO + SupervisorJob())
    
    override fun onSuccess(call: Call, response: Response) {
        try {
            val responseBody = response.body?.string() ?: ""
            
            // 使用SimpleXmlParser解析XML，检查是否需要重试
            val shouldRetry = try {
                val parser = SimpleXmlParser()
                val parseResult = parser.parseContent(responseBody)
                
                // 检查解析结果是否包含错误信息
                !parseResult.isSuccess && parseResult.errorMessage?.contains("很抱歉，系统繁忙，请稍后再试!") == true
            } catch (e: Exception) {
                // 如果解析失败，不进行重试
                false
            }
            
            if (shouldRetry && currentRetryCount < maxRetries) {
                // 需要重试
                currentRetryCount++
                println("检测到XML错误信息，正在进行第 $currentRetryCount 次重试...")
                
                // 延迟后重新发起请求
                retryScope.launch {
                    delay(retryDelay)
                    retryRequest()
                }
            } else {
                // 不需要重试或已达到最大重试次数，调用原始回调
                if (shouldRetry && currentRetryCount >= maxRetries) {
                    println("已达到最大重试次数($maxRetries)，停止重试")
                }
                
                // 重新创建Response对象，因为body已经被读取
                val newResponse = response.newBuilder()
                    .body(okhttp3.ResponseBody.create(
                        response.body?.contentType(),
                        responseBody
                    ))
                    .build()
                
                originalCallback.onSuccess(call, newResponse)
            }
            
        } catch (e: Exception) {
            originalCallback.onSuccess(call, response)
        }
    }
    
    override fun onFailure(call: Call, error: IOException) {
        originalCallback.onFailure(call, error)
    }
}
